package com.android.qjpmc.application_module.home.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.android.qjpmc.R;
import com.android.qjpmc.application_module.home.model.StationDataModel;
import com.android.qjpmc.application_module.home.viewModel.HomePageViewModel;
import com.android.qjpmc.application_module.pop.ListCheckPopupWindow;
import com.android.qjpmc.bean.DeviceStatusInfoBean;
import com.android.qjpmc.bean.ListCheckPopBean;
import com.android.qjpmc.bean.PwrDeviceBean;
import com.android.qjpmc.bean.PwrDeviceBean;
import com.android.qjpmc.data_module.PwrDataModule;
import com.android.qjpmc.data_module.PwrStation;
import com.android.qjpmc.databinding.DeviceItemDataBinding;
import com.android.qjpmc.databinding.FragmentScanStationListBinding;
import com.android.qjpmc.databinding.FragmentStationListBinding;
import com.android.qjpmc.databinding.ItemStationBinding;
import com.android.qjpmc.databinding.ItemStationDeviceBinding;
import com.android.qjpmc.databinding.ItemStationScanDeviceBinding;
import com.android.qjpmc.manager.IntentManager;
import com.android.qjpmc.permissions.PermissionsManager;
import com.android.qjpmc.widget.databindingadapter.BaseBindingItemPresenter;
import com.android.qjpmc.widget.databindingadapter.BaseDataBindingDecorator;
import com.android.qjpmc.widget.databindingadapter.SingleTypeBindingAdapter;
import com.android.qjpmc.widget.dialogfragment.InputStationDialogFragment;
import com.android.qjpmc.widget.manager.SPManager;
import com.android.qjpmc.widget.mvvm.factory.CreateViewModel;
import com.android.qjpmc.widget.mvvm.view.BaseMVVMFragment;
import com.android.qjpmc.widget.permissions.PermissionListener;
import com.android.qjpmc.widget.permissions.PermissionsUtil;
import com.android.qjpmc.widget.retrofithelper.rxsubscriber.CommonObserver;
import com.android.qjpmc.widget.retrofithelper.rxsubscriber.ProgressObserver;
import com.android.qjpmc.widget.utils.ToastUtils;
import com.android.qjpmc.widget.utils.UIUtils;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CreateViewModel(HomePageViewModel.class)
public class ScanStationListFragment extends BaseMVVMFragment<HomePageViewModel, FragmentScanStationListBinding> implements BaseBindingItemPresenter<PwrDeviceBean> {

    private List<PwrDeviceBean> stationList;
    private SingleTypeBindingAdapter deviceAdapter;
    private String code;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_scan_station_list;
    }

    //没用map的原因是因为有三个字段,其次是切换的时候要用
    List<DeviceStatusInfoBean> statusList = new ArrayList<>();

    @Override
    public void initView() {
        String json = "[{\"value\":\"d\",\"label\":\"设计中\",\"color\":\"#0000CD\"},{\"value\":\"p\",\"label\":\"生产中\",\"color\":\"#008000\"},{\"value\":\"t\",\"label\":\"运输中\",\"color\":\"#87CEEB\"},{\"value\":\"r\",\"label\":\"准备安装\",\"color\":\"#00BFFF\"},{\"value\":\"i\",\"label\":\"正在安装\",\"color\":\"#FF2020\"},{\"value\":\"c\",\"label\":\"安装完毕\",\"color\":\"#3CB371\"},{\"value\":\"u\",\"label\":\"其它\",\"color\":\"#A9A9A9\"}]";
        statusList = JSON.parseArray(json, DeviceStatusInfoBean.class);
        mBinding.setView(this);
        String loginInfo = SPManager.LoginInfo.getLoginInfo();
        mBinding.loginUserName.setText(loginInfo);

    }

    @Override
    public void initData() {
    }

    @Override
    public void initEvent() {

    }

    InputStationDialogFragment inputStationDialogFragment;

    public void onScanCode() {
        String[] permissions = {
                Manifest.permission.CAMERA,

        };
        PermissionsUtil.TipInfo info = new PermissionsUtil.TipInfo
                (UIUtils.getString(R.string.hint),
                        "需要相机权限,请同意此权限,否则将不能使用此功能",
                        "不同意",
                        "同意");

        PermissionsUtil.requestPermission(mActivity, new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permission) {
                IntentManager.toScanActivity(mActivity);
            }

            @Override
            public void permissionDenied(@NonNull String[] permission) {
            }
        }, permissions, true, info);
    }

    public void onQueryInputCode() {
        String code = mBinding.etCode.getText().toString();
        if (TextUtils.isEmpty(code)) {
            ToastUtils.showShort("请输入code");
            return;
        }
        queryCodeInfo(code);
    }

    public void queryCodeInfo(String code) {
        Logger.d("queryCodeInfo==" + code);
        if (TextUtils.isEmpty(code)) {
            ToastUtils.showShort("请输入正确的编码格式");
            return;
        }
        String[] codes = code.split("\\.");
        if (codes.length != 2) {
            ToastUtils.showShort("请输入正确的编码格式");
            return;
        }
        this.code = code;
        StationDataModel.getStationOfCompanyAndDevice(codes[0], codes[1]).subscribe(new ProgressObserver<List<PwrDeviceBean>>(false, null) {
            @Override
            public void _onNext(List<PwrDeviceBean> pwrDeviceBeans) {
                returnSiteStationData(pwrDeviceBeans);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logger.d("requestCode===" + requestCode + "====" + resultCode);
        if (requestCode == 10000 && resultCode == 10001) {
            String codeValue = data.getStringExtra("codeValue");
            queryCodeInfo(codeValue);
        }
    }

    public void onMyData() {
        IntentManager.toUserInformationActivity(mActivity);
    }


    public void returnSiteStationData(List<PwrDeviceBean> PwrDeviceBeans) {

        if (PwrDeviceBeans.size() == 0) {
            mBinding.tvDeviceNumber.setText("未查询到设备");
            mBinding.recyclerView.setVisibility(View.GONE);
            mBinding.tvDeviceNumber.setVisibility(View.GONE);
        } else {
            mBinding.recyclerView.setVisibility(View.VISIBLE);
            mBinding.tvDeviceNumber.setVisibility(View.VISIBLE);
            mBinding.tvDeviceNumber.setText("共有" + PwrDeviceBeans.size() + "个设备");
        }
        this.stationList = PwrDeviceBeans;
        deviceAdapter = new SingleTypeBindingAdapter(mActivity, stationList, R.layout.item_station_scan_device);
        mBinding.recyclerView.setAdapter(deviceAdapter);
        deviceAdapter.setItemPresenter(this);
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        deviceAdapter.setItemDecorator((BaseDataBindingDecorator<PwrDeviceBean, ItemStationScanDeviceBinding>) (binding, position, viewType, data) -> {
            String typeDesc = data.type_desc;
            int imageRes = R.drawable.ic_device_image_liang;
            if (typeDesc != null) {
                if (typeDesc.contains("墙")) {
                    imageRes = R.drawable.ic_device_image_qiang;
                    if (typeDesc.toUpperCase().contains("L")) {
                        imageRes = R.drawable.ic_device_image_qiang_l;
                    } else if (typeDesc.toUpperCase().contains("U")) {
                        imageRes = R.drawable.ic_device_image_qiang_u;
                    }

                } else if (typeDesc.contains("柱")) {
                    imageRes = R.drawable.ic_device_image_zhu;
                } else if (typeDesc.contains("板")) {
                    imageRes = R.drawable.ic_device_image_ban;
                }
            }
            binding.ivImage.setImageResource(imageRes);
            binding.tvDeviceName.setText("设备名称: " + data.deviceName);
            binding.tvDeviceNum.setText("设备编号: " + data.deviceNum);
            binding.tvCompanyName.setText("项目名称: " + data.company_name);
            String deviceStatus = data.deviceStatus;
            String deviceStatusText = "未知";
            String deviceStatusColor = "#eb5505";
            for (DeviceStatusInfoBean status : statusList) {
                if (status.getValue().equals(deviceStatus)) {
                    deviceStatusColor = status.color;
                    deviceStatusText = status.label;
                    break;
                }
            }
            binding.tvDeviceStatus.setText("设备状态: " + deviceStatusText);
            binding.tvDeviceStatus.setTextColor(Color.parseColor(deviceStatusColor));
            binding.startButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    IntentManager.toSensorDataActivity(mActivity, data.deviceCode, data.companyCode, data.groupId);
                }
            });

        });
    }


    @Override
    public void onItemClick(int position, PwrDeviceBean itemData) {
        String deviceStatus = itemData.deviceStatus;
        if (deviceStatus == null) {
            deviceStatus = "";
        }
        ListCheckPopupWindow queryApiPopupWindow = new ListCheckPopupWindow(mActivity);
        List<ListCheckPopBean> popListData = new ArrayList<>();
        for (DeviceStatusInfoBean status : statusList) {
            popListData.add(new ListCheckPopBean(status.getValue(), status.getLabel(), deviceStatus.equals(status.getValue())));
        }
        queryApiPopupWindow.initListData(popListData);
        queryApiPopupWindow.setListCheckPopupWindowListener(new ListCheckPopupWindow.ListCheckPopupWindowListener() {
            @Override
            public void onPopChooseResult(List<ListCheckPopBean> popListData) {

                ListCheckPopBean popListDatumTemp = null;
                for (ListCheckPopBean popListDatum : popListData) {
                    if (popListDatum.isOpen) {
                        popListDatumTemp = popListDatum;
                        break;
                    }
                }
                if (popListDatumTemp == null) {
                    return;
                }
                itemData.deviceStatus = popListDatumTemp.id;
                deviceAdapter.notifyDataSetChanged();
                Map<String, Object> deviceMap = new HashMap<>();
                deviceMap.put("device_code", itemData.deviceCode);
                deviceMap.put("_id", itemData.groupId);
                deviceMap.put("parent_device_id", itemData.parent_device_id);
                deviceMap.put("device_name", itemData.deviceName);
                deviceMap.put("device_num", itemData.deviceNum);
                deviceMap.put("device_status", itemData.deviceStatus);
                deviceMap.put("company_id", itemData.companyId);
                deviceMap.put("company_code", itemData.companyCode);
                deviceMap.put("device_type_id", itemData.device_type_id);
                deviceMap.put("device_type_code", itemData.device_type_code);
                deviceMap.put("type_desc", itemData.type_desc);

                StationDataModel.saveDeviceInfo(deviceMap).subscribe(new CommonObserver(
                ) {
                    @Override
                    public void onNext(Object o) {
                        super.onNext(o);
                        ToastUtils.showShort("状态修改成功");
                        Map<String, Object> realTimeMap = new HashMap<>();
                        realTimeMap.put("msg", itemData.companyCode + "." + itemData.groupId);
                        realTimeMap.put("value", 1);
                        realTimeMap.put("point_code", itemData.companyCode + ".dev_client.s_notify");
                        List<Map<String, Object>> list = new ArrayList<>();
                        list.add(realTimeMap);
                        StationDataModel.setDataRealtime(list).subscribe(new CommonObserver<Object>() {
                        });
                    }
                });


            }
        });
        View view = mActivity.getWindow().getDecorView();
        queryApiPopupWindow.showPopupWindowAtLocation(view);
    }


}
